import axios from 'axios'

const config = {
    baseURL: import.meta.env.VITE_API_URL,
    timeout: 50000,
    withCredentials: true
}

class RequestHttp {
    constructor (config) {
        // 1.实例化axios
        this.service = axios.create(config)

        // 2.请求拦截器
        this.service.interceptors.request.use(
            (config) => {
                return {...config, headers: {
                    ...config.headers,
                    "x-access-token": '' // 添加头部信息
                }}
            },
            (error) => {
                return Promise.reject(error)
            }
        )

        // 3.响应拦截器
        this.service.interceptors.response.use(
            (response) => {
                const { data } = response
                // 错误代码处理判断

                return data
            },
            (error) => {
                // 可判断超时
                return Promise.reject(error)
            }
        )
    }

    get (url, params, _object = {}) {
        return this.service.get(url, { params, ..._object })
    }
    post (url, params,_object = {}) {
        return this.service.post(url, params, _object);
    }
    put (url, params, _object = {}) {
        return this.service.put(url, params, _object);
    }
    delete (url, params, _object) {
        return this.service.delete(url, { params, ..._object })
    }
}

export default new RequestHttp(config)